import type { Todo, HistoryRecord } from "@/types"

export class StorageService {
  private static instance: StorageService
  private readonly TODOS_KEY = "todos"
  private readonly HISTORY_KEY = "todo_history"
  private readonly LANGUAGE_KEY = "language"
  private readonly BACKUP_KEY = "todo_backup"

  static getInstance(): StorageService {
    if (!StorageService.instance) {
      StorageService.instance = new StorageService()
    }
    return StorageService.instance
  }

  // Todo operations
  saveTodos(todos: Todo[]): void {
    try {
      localStorage.setItem(this.TODOS_KEY, JSON.stringify(todos))
    } catch (error) {
      console.error("Failed to save todos:", error)
    }
  }

  loadTodos(): Todo[] {
    try {
      const saved = localStorage.getItem(this.TODOS_KEY)
      if (saved) {
        return JSON.parse(saved).map((todo: any) => ({
          ...todo,
          createdAt: new Date(todo.createdAt),
          completedAt: todo.completedAt ? new Date(todo.completedAt) : undefined,
        }))
      }
    } catch (error) {
      console.error("Failed to load todos:", error)
    }
    return []
  }

  // History operations
  saveHistory(history: HistoryRecord[]): void {
    try {
      localStorage.setItem(this.HISTORY_KEY, JSON.stringify(history))
    } catch (error) {
      console.error("Failed to save history:", error)
    }
  }

  loadHistory(): HistoryRecord[] {
    try {
      const saved = localStorage.getItem(this.HISTORY_KEY)
      if (saved) {
        return JSON.parse(saved).map((record: any) => ({
          ...record,
          createdTasks: record.createdTasks.map((todo: any) => ({
            ...todo,
            createdAt: new Date(todo.createdAt),
            completedAt: todo.completedAt ? new Date(todo.completedAt) : undefined,
          })),
          completedTasks: record.completedTasks.map((todo: any) => ({
            ...todo,
            createdAt: new Date(todo.createdAt),
            completedAt: todo.completedAt ? new Date(todo.completedAt) : undefined,
          })),
        }))
      }
    } catch (error) {
      console.error("Failed to load history:", error)
    }
    return []
  }

  // Language operations
  saveLanguage(langCode: string): void {
    try {
      localStorage.setItem(this.LANGUAGE_KEY, langCode)
    } catch (error) {
      console.error("Failed to save language:", error)
    }
  }

  loadLanguage(): string | null {
    try {
      return localStorage.getItem(this.LANGUAGE_KEY)
    } catch (error) {
      console.error("Failed to load language:", error)
      return null
    }
  }

  // Backup operations
  createBackup(): string {
    try {
      const backup = {
        todos: this.loadTodos(),
        history: this.loadHistory(),
        language: this.loadLanguage(),
        timestamp: new Date().toISOString(),
      }
      const backupString = JSON.stringify(backup, null, 2)
      localStorage.setItem(this.BACKUP_KEY, backupString)
      return backupString
    } catch (error) {
      console.error("Failed to create backup:", error)
      throw error
    }
  }

  restoreFromBackup(backupData: string): void {
    try {
      const backup = JSON.parse(backupData)
      if (backup.todos) {
        localStorage.setItem(this.TODOS_KEY, JSON.stringify(backup.todos))
      }
      if (backup.history) {
        localStorage.setItem(this.HISTORY_KEY, JSON.stringify(backup.history))
      }
      if (backup.language) {
        localStorage.setItem(this.LANGUAGE_KEY, backup.language)
      }
    } catch (error) {
      console.error("Failed to restore backup:", error)
      throw error
    }
  }

  // Clear all data
  clearAllData(): void {
    try {
      localStorage.removeItem(this.TODOS_KEY)
      localStorage.removeItem(this.HISTORY_KEY)
      localStorage.removeItem(this.BACKUP_KEY)
    } catch (error) {
      console.error("Failed to clear data:", error)
    }
  }
}
